import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LoginInfoService } from '../services/login-info.service';
import { EventService } from '../services/QaService';
import {BaseUiService } from './base-ui.service';

@Injectable()
export class CommonInterceptor implements HttpInterceptor {
  public userInfo:any
   ignoreToken = ['login'];
  constructor(
    public LoginInfoService: LoginInfoService,
    public eventService: EventService,
    public baseUi:BaseUiService
  ){
    this.userInfo = this.LoginInfoService.getInfo();
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const url = req.url;
    // 过滤掉不需要token的请求
    if (url.indexOf("login") == -1) {
      console.log("----inter----", this.LoginInfoService.getToken())
      req = req.clone({ url, headers: req.headers.set('token', this.LoginInfoService.getToken()) });
    } else {
        req = req.clone({
            url
        });
    }
    return next.handle(req).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            if (event.body.code == 503) {//登录超时 跳转登录
              this.baseUi.showToast('登录超时 ，请重新登录','warning','top');
                this.eventService.eventEmitter.emit('userInfo');    
                return false;
            }
          }
        },
        error => {
          this.baseUi.showToast('服务异常','warning','top');
          
          // token过期 服务器错误等处理
        })
    );
  }
}